/**
 * TodoForm
 *
 */

import React, { FunctionComponent, ChangeEvent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import { createSelector } from 'reselect';
import { Input, Checkbox } from 'antd';
import { AppState } from '../../Stores';
import { changeAdder, toggleAll } from '../../Stores/Todo/AdderForm/action';
import { addTodo } from '../../Stores/Todo/TodoList/action';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import styles from './index.scss';

export interface TodoFormProps {
  value: string;
  isAllCompleted: boolean;
  changeAdder: (val: string) => void;
  toggleAll: (checked: boolean) => void;
  addTodo: (title: string) => void;
}

const TodoForm: FunctionComponent<TodoFormProps> = ({ value, isAllCompleted, ...props }) => {
  const onChangeHandler = (event: ChangeEvent<HTMLInputElement>) => props.changeAdder(event.target.value);
  const onToggleAllTodo = (event: CheckboxChangeEvent) => props.toggleAll(event.target.checked);
  const onPressEnter = () => {
    if (value && value.trim()) {
      props.addTodo(value);
    }
  };

  return (
    <Input
      className={styles.todoForm}
      prefix={<Checkbox checked={isAllCompleted} onChange={onToggleAllTodo} />}
      placeholder="输入待办项"
      value={value}
      onChange={onChangeHandler}
      onPressEnter={onPressEnter}
    />
  );
};

const getTodoList = (state: AppState) => state.todo.list;
const getAllSelected = createSelector(
  [getTodoList],
  list => list.length > 0 && list.filter(item => item.isCompleted).length === list.length
);

const mapStateToProps = (state: AppState) => ({
  value: state.todo.adderForm.value,
  isAllCompleted: getAllSelected(state)
});

const mapDispatchToProps = (dispatch: Dispatch) =>
  bindActionCreators(
    {
      changeAdder,
      toggleAll,
      addTodo
    },
    dispatch
  );

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoForm);
